/**
 * 2013-6-23 下午11:32:43 Created By niexiaoqiang
 */

package com.xiaoqiang.util.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import android.os.Environment;

import com.xiaoqiang.util.Logger;
import com.xiaoqiang.util.download.event.DownLoadSizeChangedEvent;
import com.xiaoqiang.util.download.listener.DownLoadSizeChangedListener;

/**
 * 下载工具类
 */
public class HttpDownload {

	private String loadFilepath;
	private String loadFilename;
	private File downloadFile;
	private FileOutputStream outputStream;
	private Collection<DownLoadSizeChangedListener> listeners;
	private boolean isdown = false;

	private static Logger log = new Logger(HttpDownload.class);

	public HttpDownload(String loadFilename) {
		this.loadFilename = loadFilename;
		this.loadFilepath = Environment.getExternalStorageDirectory() + "/mtw";
		try {
			log.debug("delete old file,create new file" + loadFilename);
			downloadFile = downlaodbefore();
		}
		catch (IOException e) {
			log.equals(e);
		}
	}

	/**
	 * @function 下载文件
	 * @param urlString
	 * @throws Exception
	 */
	public void DownFile(String urlString) throws Exception {
		int FileLength;
		int DownedFileLength = 0;
		URL url = new URL(urlString);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		InputStream inputStream = connection.getInputStream();
		outputStream = new FileOutputStream(downloadFile);
		byte[] buffer = new byte[1024];
		// 要下载的文件的长度
		FileLength = connection.getContentLength();
		// 发送数据到downloadHandle中，用以更新进度条
		notifyListeners(new DownLoadSizeChangedEvent(new DownLoadObjectInfo(loadFilename, FileLength, DownedFileLength)));

		while (DownedFileLength < FileLength && !isdown) {
			int read = inputStream.read(buffer);
			log.debug("get " + String.valueOf(read) + "byte");
			DownedFileLength += read;
			notifyListeners(new DownLoadSizeChangedEvent(new DownLoadObjectInfo(loadFilename, FileLength, DownedFileLength)));
			outputStream.write(buffer, 0, read);
		}
		// 循环完成时，文件已下载完成，FileLength=DownedFileLength;
		if (FileLength == DownedFileLength) {
			notifyListeners(new DownLoadSizeChangedEvent(new DownLoadObjectInfo(loadFilename, FileLength, FileLength)));
		}
		log.debug("end get file,the file size:" + String.valueOf(FileLength) + "byte");
		outputStream.close();
		inputStream.close();
	}

	/**
	 * @function 文件下载前的准备工作
	 * @return
	 * @throws IOException
	 */
	private File downlaodbefore() throws IOException {
		File loaddir = new File(loadFilepath);
		if (!loaddir.exists()) {
			loaddir.mkdir();
		}
		String savePathString = loadFilepath + "/" + loadFilename;
		File loadfile = new File(savePathString);
		// 如果已存在则删除
		if (loadfile.exists()) {
			loadfile.delete();
		}
		loadfile.createNewFile();
		return loadfile;
	}

	public void addServerMsgListener(DownLoadSizeChangedListener listener) {
		if (listeners == null) {
			listeners = new HashSet<DownLoadSizeChangedListener>();
		}
		listeners.add(listener);
		log.debug("add listener:" + listener.getClass());
	}

	public void removeServerMsgListener(DownLoadSizeChangedListener listener) {
		if (listeners == null) {
			return;
		}
		listeners.remove(listener);
	}

	public void notifyListeners(DownLoadSizeChangedEvent event) {
		Iterator<DownLoadSizeChangedListener> iter = listeners.iterator();
		while (iter.hasNext()) {
			DownLoadSizeChangedListener listener = (DownLoadSizeChangedListener) iter.next();
			listener.downLoadSizeChanged(event);
			log.debug("notify the listener:" + listener.getClass());
		}
	}

	public void setIsdown(boolean isdown) {
		this.isdown = isdown;
	}

}
